<?php

namespace App\Models\Voter;

use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class WxVoter extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'wx_voter';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
        });

        static::created(function ($model) {

        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'status'){
                    $originalValue = $original[$key] ?? 0;
                    if($value == 1){
                        if($originalValue == 0){
                            UserUtils::add_user_notice(8001, $model->user_id,'创建选票活动审核通过','您创建的"<a href="/pagesV/voter/detail/detail?id='.$model->id.'">'.$model->title.'</a>"选票活动审核已通过，快去分享给小伙伴们吧',100);
                        }
                    }else{
                        if($originalValue == 1){
                            UserUtils::add_user_notice(8001, $model->user_id,'选手报名审核失败','您创建的"<a href="/pagesV/voter/detail/detail?id='.$model->id.'">'.$model->title.'</a>"选票活动审核失败，经审核，您提交的资料不合法',100);
                        }
                    }
                }
            }
        });
        static::deleted(function ($model) {
            WxChat::where('expand_type', 104)->where('expand_id', $model->id)->forceDelete();
        });
        // 其他的模型事件监听...
    }


    public function getMasterUserAvatarAttribute($value){
        if($value){
            return $value . '?imageMogr2/thumbnail/50x50/crop/50x50/gravity/center/format/webp/interlace/1/quality/100';
        }
        return '';
    }

    public function getBannersAttribute($value){
        if($value && is_string($value)){
            return json_decode($value, true);
        }
        return [];
    }

    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

}
